/**
 * 资产模块状态
 */
import api from '@/api'

const state = {
  // 资产列表
  assetList: [],
  // 分页信息
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1
  },
  // 查询参数
  queryParams: {
    category: '',
    status: '',
    keyword: '',
    page: 1,
    pageSize: 10
  },
  // 当前资产详情
  currentAsset: null,
  // 资产类别
  categories: [],
  // 资产状态选项
  statusOptions: [],
  // 加载状态
  loading: false,
  // 是否处于加载更多状态
  loadingMore: false
}

const mutations = {
  // 设置资产列表
  SET_ASSET_LIST: (state, { list, pagination, append = false }) => {
    if (append) {
      // 追加模式，用于无限滚动
      state.assetList = [...state.assetList, ...list]
    } else {
      // 替换模式，用于初始加载或筛选
      state.assetList = list
    }
    
    if (pagination) {
      state.pagination = pagination
    }
  },
  // 设置查询参数
  SET_QUERY_PARAMS: (state, params) => {
    state.queryParams = { ...state.queryParams, ...params }
  },
  // 设置当前资产详情
  SET_CURRENT_ASSET: (state, asset) => {
    state.currentAsset = asset
  },
  // 设置资产类别
  SET_CATEGORIES: (state, categories) => {
    state.categories = categories
  },
  // 设置资产状态选项
  SET_STATUS_OPTIONS: (state, options) => {
    state.statusOptions = options
  },
  // 设置加载状态
  SET_LOADING: (state, loading) => {
    state.loading = loading
  },
  // 设置加载更多状态
  SET_LOADING_MORE: (state, loading) => {
    state.loadingMore = loading
  },
  // 更新资产状态
  UPDATE_ASSET_STATUS: (state, { id, status }) => {
    const index = state.assetList.findIndex(item => item.id === id)
    if (index !== -1) {
      state.assetList[index].status = status
    }
    
    if (state.currentAsset && state.currentAsset.id === id) {
      state.currentAsset.status = status
    }
  }
}

const actions = {
  // 获取资产列表
  getAssetList({ commit, state }, params = {}) {
    // 是否为加载更多操作
    const isLoadMore = params.append || false
    
    // 设置相应的加载状态
    if (isLoadMore) {
      commit('SET_LOADING_MORE', true)
    } else {
      commit('SET_LOADING', true)
    }
    
    // 合并查询参数
    const queryParams = { ...state.queryParams, ...params }
    commit('SET_QUERY_PARAMS', queryParams)
    
    // 调用API
    return api.asset.getAssetList(queryParams)
      .then(response => {
        const { list, pagination } = response
        commit('SET_ASSET_LIST', { list, pagination, append: isLoadMore })
        return list // 返回数据列表，便于判断是否到底
      })
      .finally(() => {
        if (isLoadMore) {
          commit('SET_LOADING_MORE', false)
        } else {
          commit('SET_LOADING', false)
        }
      })
  },
  
  // 获取资产详情
  getAssetDetail({ commit }, id) {
    commit('SET_LOADING', true)
    
    return api.asset.getAssetDetail(id)
      .then(response => {
        commit('SET_CURRENT_ASSET', response)
        return response
      })
      .finally(() => {
        commit('SET_LOADING', false)
      })
  },
  
  // 获取资产类别
  getAssetCategories({ commit }) {
    return api.asset.getAssetCategories()
      .then(response => {
        commit('SET_CATEGORIES', response)
        return response
      })
  },
  
  // 申请资产领用
  applyAsset({ commit }, data) {
    commit('SET_LOADING', true)
    
    return api.asset.applyAsset(data)
      .then(response => {
        return response
      })
      .finally(() => {
        commit('SET_LOADING', false)
      })
  },
  
  // 申请资产维修
  repairAsset({ commit }, data) {
    commit('SET_LOADING', true)
    
    return api.asset.repairAsset(data)
      .then(response => {
        return response
      })
      .finally(() => {
        commit('SET_LOADING', false)
      })
  },
  
  // 更新资产状态
  updateAssetStatus({ commit }, { id, data }) {
    commit('SET_LOADING', true)
    
    return api.asset.updateAssetStatus(id, data)
      .then(() => {
        commit('UPDATE_ASSET_STATUS', { id, status: data.status })
        return { success: true }
      })
      .finally(() => {
        commit('SET_LOADING', false)
      })
  },
  
  // 更新查询参数
  updateQueryParams({ commit, dispatch }, params) {
    // 重置页码
    params.page = 1
    
    commit('SET_QUERY_PARAMS', params)
    // 清空列表，准备重新加载
    commit('SET_ASSET_LIST', { list: [], pagination: null })
    // 重新获取列表
    return dispatch('getAssetList')
  },
  
  // 搜索资产
  searchAssets({ dispatch }, keyword) {
    return dispatch('updateQueryParams', { keyword, page: 1 })
  },
  
  // 加载更多资产
  loadMoreAssets({ state, dispatch }) {
    if (state.loading || state.loadingMore) return Promise.resolve([])
    
    const nextPage = state.queryParams.page + 1
    return dispatch('getAssetList', {
      page: nextPage,
      append: true
    })
  },
  
  // 刷新资产列表
  refreshAssetList({ commit, dispatch, state }) {
    // 保持当前的过滤条件，但重置页码
    const params = {
      ...state.queryParams,
      page: 1
    }
    
    // 清空当前列表
    commit('SET_ASSET_LIST', { list: [], pagination: null })
    
    // 重新加载第一页
    return dispatch('getAssetList', params)
  }
}

const getters = {
  // 获取资产总数
  totalAssets: (state) => {
    return state.pagination.total || 0
  },
  // 获取资产类别名称
  getCategoryName: (state) => (id) => {
    const category = state.categories.find(item => item.id === id)
    return category ? category.name : ''
  },
  // 获取资产状态名称
  getStatusName: (state) => (id) => {
    const status = state.statusOptions.find(item => item.id === id)
    return status ? status.name : ''
  },
  // 按类别分组的资产数量
  assetCountByCategory: (state) => {
    return state.categories.map(category => {
      const count = state.assetList.filter(asset => 
        asset.category && asset.category.id === category.id
      ).length
      return {
        category: category.name,
        count
      }
    })
  },
  // 是否已经加载所有数据
  hasReachedEnd: (state) => {
    if (!state.pagination) return false
    return state.assetList.length >= state.pagination.total
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 